package com.gaga.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.gaga.common.constant.Constants;
import com.gaga.common.entity.file.FastDFSFile;
import com.gaga.common.entity.file.FileDesc;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class FileManageUtils {


    public static String getFileExtName(String fileName) {
        String[] splitName = fileName.split("\\.");
        return splitName[splitName.length - 1];
    }

    public static FileDesc upload(FastDFSFile file, FileDesc fileDesc) throws Exception {

        long startTime = System.currentTimeMillis();

        //文件如果不存在，则保存，否则直接返回文件的MD5名
        String path = fileDesc.getPath() + File.separator +
                (StringUtils.isBlank(fileDesc.getSuperPath()) ? "" : fileDesc.getSuperPath());
        String uuidFileName = file.getMd5();
        String destinationFileName = uuidFileName + "." + file.getExt();
        File localFile = new File(path, destinationFileName);

        //判断文件是否可以上传
        if (!Arrays.asList(Constants.FILE_SUFFIX_WHITE_ARR).contains(file.getExt())) {
            throw new Exception("文件上传失败,文件是不合法文件");
        }

        if (fileDesc.getIsReNameIfHasSameName() && FileUtil.isDirectory(path)) {
            //去查一下是不是存在名称相同的，如果
            List<String> listFileNames = FileUtil.listFileNames(path);
            if (listFileNames.size() > 0) {
                List<String> collect = listFileNames.stream().filter(item -> item.contains(uuidFileName)).collect(Collectors.toList());
                if (collect != null && collect.size() > 0) {
                    destinationFileName = uuidFileName + "_(" + collect.size() + ")" + "." + file.getExt();
                    localFile = new File(path, destinationFileName);
                }
            }
        }
        if (FileUtil.exist(localFile)) {
            FileUtil.del(localFile);
        }

        //创建一个新文件
        File attachFile = FileUtil.touch(path, destinationFileName);
        log.debug("文件为:{}", JSON.toJSONString(attachFile));
        //将文件流写入文件中
        FileUtil.writeBytes(file.getContent(), attachFile);
        fileDesc.setPath("/files/" + (StringUtils.isNotBlank(fileDesc.getSuperPath()) ? fileDesc.getSuperPath() : StringUtils.EMPTY) + "/" + destinationFileName);

        fileDesc.setAbsolutePath(fileDesc.getServerPath() + "files/" +
                (StringUtils.isNotBlank(fileDesc.getSuperPath()) ? fileDesc.getSuperPath() : StringUtils.EMPTY) + "/" + destinationFileName);

        if (fileDesc.getIsUnZip()) {
            log.debug("文件路径为:{}", attachFile.getPath());
            ZipUtil.unzip(attachFile.getPath());
            //解压完成之后，对于文件检索一下，如果不是图片类型的直接删除掉，返回出现问题
            List<File> filesList = FileUtil.loopFiles(path + "/" + uuidFileName);
            filesList.forEach(
                    itemFile -> {
                        String fileName = itemFile.getName();
                        String fileExtName = getFileExtName(fileName);
                        if (!Arrays.asList(Constants.FILE_SUFFIX_WHITE_ARR).contains(fileExtName)) {
                            FileUtil.del(itemFile.getPath());
                        }
                        // 去除文件的空格
                        if (fileName.indexOf(" ") >= 0) {
                            fileName = fileName.replaceAll("\\s*", "");
                            FileUtil.rename(itemFile, fileName, false, true);
                        }
                    });

            FileUtil.del(attachFile.getPath());
        }

        long endTime = System.currentTimeMillis();
        log.debug("currentTimeMillis: ", endTime - startTime);

        return fileDesc;
    }
}
